package tcpserver.handler.in;

import frame.laxcen.BaseFrame;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import tcpserver.RFIDSession;
import tcpserver.RFIDSessionManager;

import java.util.List;
import java.util.concurrent.BlockingQueue;

public class FrameCollector extends ChannelInboundHandlerAdapter {

    private final static RFIDSessionManager manager = RFIDSessionManager.instance;

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        RFIDSession session = manager.get(ctx.channel());

        List<BaseFrame> overflow = session.getOverflow();

        BlockingQueue<BaseFrame> queue = session.getQueue();

        overflow.add(BaseFrame.class.cast(msg));

        while(overflow.size() > 0 && queue.offer(overflow.get(0))) overflow.remove(0);

        ctx.fireChannelRead(overflow.size());
    }
}
